package com.cgycms.prototype.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cgycms.prototype.SitePrototypeService;
import com.cgycms.prototype.UserService;
import com.cgycms.prototype.cache.TimeCacheUtils;
import com.cgycms.prototype.common.BizException;
import com.cgycms.prototype.constant.ServiceCacheKeyConstant;
import com.cgycms.prototype.entity.LoginUserEntity;
import com.cgycms.prototype.entity.SiteEntity;
import com.cgycms.prototype.mapper.UserMapper;
import com.cgycms.prototype.model.UserModel;
import com.cgycms.prototype.model.UserTokenModel;
import com.cgycms.prototype.util.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName UserServiceImpl
 * @Description 实现类
 * @Author 超哥呦
 * @Date 2021/11/27 21:44
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, LoginUserEntity> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private SitePrototypeService sitePrototypeService;

    @Override
    public UserTokenModel doLogin(String username, String password) {
        SiteEntity site = sitePrototypeService.querySite();
        if (site.getRoleSwitch() == 1) {
            throw new BizException("系统已关闭登录入口,请联系管理员！");
        }

        LoginUserEntity loginUserEntity = userMapper.selectUserByLogin(username);
        if (ObjectUtil.isNull(loginUserEntity)) {
            throw new BizException("账号或密码错误！");
        }

        String oldPass = loginUserEntity.getPassword();
        String newPass = SecureUtil.md5(password + loginUserEntity.getLoginName());
        if (!oldPass.equals(newPass)) {
            throw new BizException("账号或密码错误！");
        }
        StpUtil.login(loginUserEntity.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        UserTokenModel userTokenModel = new UserTokenModel();
        BeanUtils.copyProperties(loginUserEntity, userTokenModel);
        userTokenModel.setToken(tokenInfo.getTokenValue());
        userTokenModel.setTokenTime(tokenInfo.getTokenTimeout());
        //只有ID1为超级管理员
        userTokenModel.setSuperAdmin(loginUserEntity.getId() == 1L ? true : false);
        StpUtil.getTokenSession().set("user", userTokenModel);
        return userTokenModel;
    }

    @Override
    public Integer selectUserByLoginNameCount(String loginName) {
        return userMapper.selectUserByLoginNameCount(loginName);
    }

    @Override
    public Map<Long, UserModel> queryUserMap() {
        List<UserModel> userModelList = (List<UserModel>) TimeCacheUtils.get(ServiceCacheKeyConstant.SYS_USERS_ALL);
        if (ObjectUtil.isNull(userModelList)) {
            userModelList = userMapper.queryUserList();
            if (ObjectUtil.isNotNull(userModelList)) {
                TimeCacheUtils.put(ServiceCacheKeyConstant.SYS_USERS_ALL, userModelList);
            }
        }
        if (ObjectUtil.isNotNull(userModelList)) {
            return userModelList.stream().collect(Collectors.toMap(UserModel::getId, Function.identity(), (k, v) -> v));
        }
        return new HashMap<>(0);
    }

    @Override
    public List<UserTokenModel> queryUserList() {
        List<UserModel> userModels = userMapper.queryUserList();
        List<UserTokenModel> resultList = new ArrayList<>(userModels.size());
        for (UserModel userModel : userModels) {
            UserTokenModel item = new UserTokenModel();
            BeanUtils.copyProperties(userModel, item);
            resultList.add(item);
        }
        return resultList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Object deleteBatchUser(List<Long> ids) {
        for (Long id : ids) {
            if(id==1L){
                throw new BizException("超级管理员账号不允许删除！");
            }
            userMapper.deleteById(id);
            UserUtils.kicking(id);
        }
        return "删除成功!";
    }
}
